package com.citas.client.widget;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Set;
import java.util.TreeSet;

import com.citas.client.CitasConstants;
import com.citas.client.CitasMessages;
import com.citas.client.Display;
import com.citas.client.Getdata;
import com.citas.client.GetdataAsync;
import com.citas.shared.CitasModel;
import com.google.gwt.cell.client.ButtonCell;
import com.google.gwt.cell.client.FieldUpdater;
import com.google.gwt.cell.client.Cell.Context;
import com.google.gwt.core.client.GWT;
import com.google.gwt.dev.resource.Resource;
//import com.google.gwt.core.ext.soyc.Range;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.safehtml.shared.SafeHtml;
import com.google.gwt.safehtml.shared.SafeHtmlBuilder;
import com.google.gwt.safehtml.shared.SafeHtmlUtils;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.uibinder.client.UiHandler;
import com.google.gwt.user.cellview.client.CellTable;
import com.google.gwt.user.cellview.client.Column;
import com.google.gwt.user.cellview.client.RowStyles;
import com.google.gwt.user.cellview.client.SimplePager;
import com.google.gwt.user.cellview.client.SimplePager.TextLocation;
import com.google.gwt.user.cellview.client.TextColumn;
import com.google.gwt.user.client.Command;
import com.google.gwt.user.client.Cookies;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.CheckBox;
import com.google.gwt.user.client.ui.ClickListener;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.HasText;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.PopupPanel;
import com.google.gwt.user.client.ui.VerticalPanel;
import com.google.gwt.user.client.ui.Widget;
import com.google.gwt.user.datepicker.client.DateBox;
import com.google.gwt.view.client.Range;

public class PanelReservaCita extends Composite implements HasText {

	Suggest messeg=null;
	private Command comando;
	private Integer flag;
	private ArrayList<String[]> listadatosdb;
	private String Lastquery;
	private List<CitasModel> lista;
	private List<CheckBox> lischeck;
	private static PanelReservaCitaUiBinder uiBinder = GWT
			.create(PanelReservaCitaUiBinder.class);
	private CellTable.Resources tableRes = GWT.create(StyleCellTableCita.class);
	//private PopupPanel popup = new PopupPanel(true);
	@UiField CellTable<CitasModel > tabla;
	@UiField Button batras;
	@UiField DateBox fechaini;
	@UiField DateBox fechafin;
	@UiField Button buscar;
	@UiField VerticalPanel panelcell;
	@UiField CheckBox luCheck ;
	@UiField CheckBox maCheck ;
	@UiField CheckBox miCheck ;
	@UiField CheckBox juCheck ;
	@UiField CheckBox viCheck ;
	@UiField CheckBox saCheck ;
	@UiField CheckBox dmCheck ;
	@UiField Button sugerencia;
	@UiField SimplePager paginado;
	interface PanelReservaCitaUiBinder extends
	UiBinder<Widget, PanelReservaCita> {

	}

	public PanelReservaCita(Command co) {
		//CitasConstants inter=GWT.create(CitasConstants.class);
		//buscar.setText(inter.buscar());
		tabla= new CellTable<CitasModel>(15,tableRes );
		lischeck = new ArrayList<CheckBox>();
		listadatosdb= new ArrayList<String[]>();
		lista = new ArrayList<CitasModel>();
		comando=co;
		flag=0;
		
		initWidget(uiBinder.createAndBindUi(this));
		lista.clear();
		
		this.prepareTab();
		setRowData2();
		fillchecks();
		//if(messeg==null){
		//getsugerencia().mostrar();}else{messeg.mostrar();
		//}
		getsugerencia().mostrar();
		getsugerencia().addObjt(this);
	}
	
	@UiHandler("buscar")
	void onBuscarClick(ClickEvent event)
	{
		if(fechaini.getValue()!=null && fechafin.getValue()!=null )
		{

			if(fechaini.getValue().before(fechafin.getValue()))
			{
				//int especialidad = 1 ; // 
				//int establecimiento = 4 ;  
				String id_es=Cookies.getCookie("idespecialidad");
				String id_cen=Cookies.getCookie("idcentromedico");

				//luCheck.get

				String diasemana= "and diasemana in ( ";int cont=0;
				for(CheckBox ch: lischeck)
				{
					if(ch.isChecked())
					{diasemana+=ch.getFormValue()+",";cont++;}
					//diasemana="and diasemana in (";
				}if(cont!=0){diasemana=diasemana.substring(0,diasemana.length()-1)+")";}else{diasemana="";}
				System.out.println(diasemana);


				String dias= "(";  	String mese= "and mes in ( "+(fechaini.getValue().getMonth()+1)+" )";
				Set <Integer> diad= new TreeSet<Integer>(); int lastvalue=0;

				if(fechaini.getValue().getMonth()<fechafin.getValue().getMonth())
				{
					mese="and mes in (";
					for(int i=fechaini.getValue().getMonth()+1;i<=fechafin.getValue().getMonth()+1;i++)
					{mese+=i + ",";}
					lastvalue=31;
					mese=mese.substring(0,mese.length()-1)+")";
				}
				System.out.println(mese);
				for(int u =fechaini.getValue().getDate();u<=lastvalue+fechafin.getValue().getDate();u++)
				{  diad.add(u%32); }

				for(Integer as : diad){dias+=as+",";}
				//System.out.println(mese);

				dias=dias.substring(0,dias.length()-1)+")";
				//System.out.println(dias);


				String query = 
						"SELECT horario.\"confirmado\",horario.\"idhorario\", " +
								"horario.\"idagenda\"," +
								"agenda.idconsultorio, consultorio.\"nombreconsultorio\", " +
								"horario.\"horahorario\", horario.\"minutohorario\","+
								"agenda.\"anio\",agenda.\"mes\",agenda.\"dia\" "+
								"FROM consultorio INNER JOIN agenda on consultorio.idconsultorio"+
								"= agenda.idconsultorio inner join horario on agenda.\"idagenda\" = horario.\"idagenda\" and "+  
								"horario.idhorario in ("+
								"SELECT horario.idhorario from horario WHERE  horario.\"idagenda\"  in (SELECT \"idagenda\"  FROM agenda where \"idconsultorio\" in "+
								"(select \"idconsultorio\" from consultorio where \"idespecialidad\" = "+id_es+" and \"idestablecimientosalud\" = "+id_cen+")"+
								"and dia in "+dias +"" +mese+""+diasemana +" ))  order by  agenda.\"anio\" , agenda.\"mes\", agenda.\"dia\"  ";


				getDatacallback(query);
				setLastquery(query);
				//tabla.redraw();
				//	panelcell.clear();
				//panelcell.add(tabla);
				//putStyle();
				//RootPanel.get("citaPanel").clear();
				//RootPanel.get("citaPanel").add(tabla);





			}else{
				Window.alert("no permitido");
			}



		}

	}
	@UiHandler("sugerencia")
	void onSugerenciaCLick(ClickEvent event)
	{
		this.findSugg();
	}
	public boolean getDatacallback(String cadena)
	{

		GetdataAsync data = GWT.create(Getdata.class);

		if(data==null)
		{data = GWT.create(Getdata.class);}

		data.getaDatadb(cadena, new AsyncCallback<ArrayList<String[]> > (){
			@Override
			public void onFailure(Throwable caught) {
				// TODO Auto-generated method stub
				Window.alert("fallada es la consulta");
			}
			@Override
			public void onSuccess(ArrayList<String[]> result) {
				// TODO Auto-generated method stub 
				if(flag==0){
					listadatosdb=result;
					if(listadatosdb.size()!=0) 	    	
						//tabla.redraw();
					{
						//panelcell.clear();
						settoTableModel(listadatosdb);
						//setLastquery(query);
						//prepareTab();

						setRowCount2();
						setRowData2();
						System.out.println(tabla.getColumnCount());

					}
					else{Window.alert("No se encontraron Resultados");}

				}
				else{



					listadatosdb=result;
					if(listadatosdb.size()!=0){
						settoTableModel(listadatosdb);
						CitasMessages ms= GWT.create(CitasMessages.class);
						Window.alert(ms.messajeok());
						setRowData2();
						tabla.redraw();
						flag=0;
					}

				}
			}});

		return true; 

	}
	public void updateDatacallback(String cadena)
	{
		GetdataAsync data = GWT.create(Getdata.class);

		if(data==null)
		{data = GWT.create(Getdata.class);}

		data.updateDatadb(cadena, new AsyncCallback<Integer>() {

			@Override
			public void onSuccess(Integer result) {
				// TODO Auto-generated method stub
				if(result==1){
					flag=1;
					//RootPanel.get("citaPanel").add(object);

					getDatacallback(Lastquery);
					//
				}
			}

			@Override
			public void onFailure(Throwable caught) {
				// TODO Auto-generated method stub

			}
		});



	}

	public void prepareTab()
	{
		//for(int i=0;i<tabla.getColumnCount();i++)
		//tabla.removeColumn(i);


		TextColumn<CitasModel> columnid = new TextColumn<CitasModel>() {

			@Override
			public String getValue(CitasModel object) {
				// TODO Auto-generated method stub
				return Integer.toString(object.getId());
			}
		};


		TextColumn<CitasModel> columndia = new TextColumn<CitasModel>() {

			@Override
			public String getValue(CitasModel object) {
				// TODO Auto-generated method stub
				return Integer.toString(object.getDia());
			}
		};
		TextColumn<CitasModel> columnmes= new TextColumn<CitasModel>() {

			@Override
			public String getValue(CitasModel object) {
				// TODO Auto-generated method stub
				return Integer.toString(object.getMes());
			}
		};

		TextColumn<CitasModel> columnsemana = new TextColumn<CitasModel>() {

			@Override
			public String getValue(CitasModel object) {
				// TODO Auto-generated method stub
				CitasConstants me= GWT.create(CitasConstants.class);	
				String sem=(me.weeks().get(Integer.toString(object.getDiasemana())));
				return sem;
			}
		};
		TextColumn<CitasModel> columndate = new TextColumn<CitasModel>() {

			@Override
			public String getValue(CitasModel object) {
				// TODO Auto-generated method stub
				return ""+object.getHora()+":"+object.getMinuto() + " horas";
			}
		};

		ButtonCell butt = new ButtonCell();
		Column columnbutton = new Column<CitasModel, String>(butt) {
			SafeHtml disablehtml = SafeHtmlUtils.fromSafeConstant("<button type=\"button\" disabled=\"disabled\">Bloqueado</button>");
			//if(object.getDia()==2){butt.handlesSelection();}
			@Override
			public String getValue(CitasModel object) {
				// TODO Auto-generated method stub
				CitasConstants me= GWT.create(CitasConstants.class);
				return me.block();
			}

			@Override
			public void render(Context context, CitasModel object,
					SafeHtmlBuilder sb) {
				CitasConstants inter =GWT.create(CitasConstants.class); 
				if(object.getEstado().equals(inter.confirm()))
				{

					sb.append(disablehtml);
				}
				// TODO Auto-generated method stub
				else{super.render(context, object, sb);
				}}

		};

		columnbutton.setFieldUpdater(new FieldUpdater<CitasModel, String>() 
				{

			@Override
			public void update(int index, CitasModel object, String value) {
				// TODO Auto-generated method stub
				//Window.alert("clickeaste"+ object.getDia());
				CitasConstants inter =GWT.create(CitasConstants.class); 
				if(object.getEstado().equals(inter.unconfirm()))
				{
					//Window.alert("clickeaste"+ object.getDia());
					String query="UPDATE horario SET  confirmado = \'c\' WHERE idhorario ="+object.getId()+"";
					Integer respuesta=0;
					CitasMessages citmes= GWT.create(CitasMessages.class);
					if(Window.confirm(citmes.messajeregcita()))
					{
						updateDatacallback(query);
						//flag=1;

					}
				}
			}
				});
		/*this.addColumn(new ButtonCell(), "button",new String()
					{
					public String getValue(CitasModel object){
						return "click" + object.getAnio();
					}
					},new FieldUpdater<CitasModel, String>() 
					{
						public void update(){}
					});
		 */

		CitasConstants inter =GWT.create(CitasConstants.class); 
		tabla.addColumn(columnid,inter.id());
		tabla.addColumn(columndia,inter.day());
		tabla.addColumn(columnmes,"Mes");

		tabla.addColumn(columndate, inter.hour());
		tabla.addColumn(columnsemana,inter.dayweek());
		tabla.addColumn(columnbutton,inter.estate());

		//paginado.setPageSize(20);
		//paginado.setDisplay(tabla);
		tabla.setPageSize(10);
		putStyle();

	}


	public void settoTableModel(ArrayList<String[]> listadatosdb)
	{
		lista.clear();
		for (String[] str : listadatosdb)
		{
			//System.out.println(str[1]);

			lista.add(
					new CitasModel(Integer.parseInt(str[str.length-1]),
							Integer.parseInt(str[str.length-2]),
							Integer.parseInt(str[str.length-3]),
							Integer.parseInt(str[str.length-4]),
							Integer.parseInt(str[str.length-5]),
							str[0],str[1] )
					);
		}
	}
	public void setRowCount2()
	{
		tabla.setRowCount(lista.size());

	}

	public void setRowData2()
	{
		tabla.setRowData(lista);
	}
	public void mostrar(){
	
		Display.get().setWidget(this);

	}
	

	public String putStyle()
	{

		//getRowElement(rowIndex).getStyle().setBackgroundColor("#CACAFF");
		tabla.setRowStyles(new RowStyles<CitasModel>() {

			@Override
			public String getStyleNames(CitasModel row, int rowIndex) {
				// TODO Auto-generated method stub
				//return null;

				/*if(row.getDia()==4){

			getRowElement(rowIndex).getStyle().setBorderColor("#F60733");
				//getStyle().setBackgroundColor();

			}*/
				//getElement().getStyle().setBackgroundColor("#F60733");
				CitasConstants myConstants = GWT.create(CitasConstants.class);

				if(row.getEstado().equals(myConstants.confirm()))
				{
					return "free";
				}
				else{
					return "occup";
				}
			}
		});
		return null;}

	public void fillchecks()
	{
		lischeck.add(luCheck);
		lischeck.add(maCheck);
		lischeck.add(miCheck);
		lischeck.add(juCheck);
		lischeck.add(viCheck);
		lischeck.add(saCheck);
		lischeck.add(dmCheck);

	}

	public Suggest getsugerencia()
	{
		if(messeg==null){
		messeg = new Suggest(this.comando);
		}
		return messeg;
	}

	public void findSugg()
	{
		Date datanow= new Date();
		Date dataprof= new Date(112,6,30);
		//datanow.setDate(6);
		 // System.out.println(datanow.getDate());
		 // System.out.println(datanow.getMonth());//0-11
		 // System.out.println(datanow.getYear()+1900);
		  String diasemana=Integer.toString(datanow.getDay());
		  System.out.println(dataprof.getDay());
		  String dias=Integer.toString(datanow.getDate());
		  //System.out.println(dias);
		  String mese= Integer.toString(datanow.getMonth()+1);
		  //System.out.println(mese);
		  String id_es=Cookies.getCookie("idespecialidad");
		  String id_cen=Cookies.getCookie("idcentromedico");
		String query = 
				"SELECT horario.\"confirmado\",horario.\"idhorario\", " +
						"horario.\"idagenda\"," +
						"agenda.idconsultorio, consultorio.\"nombreconsultorio\", " +
						"horario.\"horahorario\", horario.\"minutohorario\","+
						"agenda.\"anio\",agenda.\"mes\",agenda.\"dia\" "+
						"FROM consultorio INNER JOIN agenda on consultorio.idconsultorio"+
						"= agenda.idconsultorio inner join horario on agenda.\"idagenda\" = horario.\"idagenda\" and "+  
						"horario.idhorario in ("+
						"SELECT horario.idhorario from horario WHERE  horario.\"idagenda\"  in (SELECT \"idagenda\"  FROM agenda where \"idconsultorio\" in "+
						"(select \"idconsultorio\" from consultorio where \"idespecialidad\" = "+id_es+" and \"idestablecimientosalud\" = "+id_cen+")"+
						"and dia in ("+dias +") and mes in(" +mese+") and diasemana in ("+diasemana +") ))  order by  agenda.\"anio\" , agenda.\"mes\", agenda.\"dia\"  ";


		getDatacallback(query);
		setLastquery(query);
		
		
	}












	@Override
	public String getText() {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public void setText(String text) {
		// TODO Auto-generated method stub

	}

	public String getLastquery() {
		return Lastquery;
	}
	public void setLastquery(String lastquery) {
		Lastquery = lastquery;
	}
	public ArrayList<String[]> getListadatosdb() {
		return listadatosdb;
	}
	public void setListadatosdb(ArrayList<String[]> listadatosdb) {
		this.listadatosdb = listadatosdb;
	}

	@UiHandler("batras")
	void onBatrasClick(ClickEvent event) {
		for(CheckBox as : lischeck){as.setValue(null);}
		fechafin.setValue(null);
		fechaini.setValue(null);
		lista.clear();
		setRowData2();
		//messeg.mostrar();
		comando.execute();
	}


}
